package com.ctrip.corp.obt.shard.holder;


import com.ctrip.corp.obt.shard.annotation.ShardModel;
import com.ctrip.corp.obt.shard.exception.ShardException;

import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author marco.zheng
 * @version 1.0
 * @date 2022/02/09
 * @desc {@link ShardModel} Holder
 * @see
 * @since 1.0
 */
public class ShardModelHolder {

    private static final Map<Method, ShardModel> shardModelCache = new ConcurrentHashMap<>();

    private ShardModelHolder() {
    }

    public static boolean contains(Method method) {
        return shardModelCache.containsKey(method);
    }

    public static void remove(Method method) {
        shardModelCache.remove(method);
    }

    public static void removeAll() {
        shardModelCache.clear();
    }

    public static ShardModel get(Method method) {
        return shardModelCache.get(method);
    }

    public static void put(Method key, ShardModel shardModel) {
        if (shardModel == null) {
            throw new ShardException("shardModel is null!");
        } else {
            if (shardModelCache.size() >= 1000) {
                shardModelCache.clear();
                shardModelCache.put(key, shardModel);
            }

            if (!shardModelCache.containsKey(key)) {
                shardModelCache.put(key, shardModel);
            }
        }
    }

    public static Map<Method, ShardModel> getShardModelCache() {
        return Collections.unmodifiableMap(shardModelCache);
    }

}
